<?php   // for user login
session_start();
include "include/dbConfig.php";
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];
?>

<?php
$studyID = $_REQUEST['studyID'];
$projectID = $_REQUEST['projectID'];
$studyName = $_REQUEST['studyName'];
$studyDescription = $_REQUEST['studyDescription'];
$actionType=$_REQUEST['actionType'];


/*if (!isset($name)) 
{
echo "<h1> Error in name </h1>";
echo "<br />";
} else */
{
// connect to mysql
	echo "<h1> connecting to db</h1>";
		$mysql = mysqli_connect("$dbservername", "$dbusername", "$dbpassword");
	if(!$mysql) {
	echo "Cannot connect to database.";
	exit;
	}
echo "<h1> connecting to db</h1>";
echo "<h1> connected db</h1>";
// select the appropriate database
	$selected = mysqli_select_db($mysql, "$dbname");
if(!$selected) {
echo "Cannot select database.";
exit;
}
	if($actionType=="Del")
	{
		$query = 'delete from user_studies  where user_id = '. $user_id." and study_id='".$studyID."'" ;
	}
	else
	{
		$query = 'select count(*) from user_studies  where user_id = '. $user_id." and project_id=".$projectID." and study_name='".$studyName."'" ;
		
		$result = mysqli_query($mysql, $query);
		var_dump($result);
		$row = mysqli_fetch_row($result);

		$count = $row[0];

		if ($count == 0) {
			echo "New User";
			$query = "insert into user_studies(user_id,project_id,study_name,study_description) values('".$user_id."','".$projectID."','".$studyName."','".$studyDescription."') " ;		
			
		}
		else
		{
			$query = "UPDATE user_studies SET study_name  = '" .$studyName. "', study_description  = '" .$studyDescription. "' where user_id = '". $user_id."' and project_id=".$projectID." and study_name='".$studyName."'" ;
			
		}
	}
$result = mysqli_query($mysql, $query);
 

echo "$query\n";

if ( $result );
{
		header("Location: /OSPMS/404.php");
	}

	header("Location: /OSPMS/Study.php?projectID=".$projectID);

}
?>


